package com.wtt.contrller;

import com.wtt.domain.Girl;
import com.wtt.domain.Result;
import com.wtt.repository.GirlRepository;
import com.wtt.service.GirlService;
import com.wtt.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by wutaotao
 * 2018/1/5
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    @GetMapping(value = "/girls")
    public List<Girl> getGirls(){
        return girlRepository.findAll();
    }

    @GetMapping(value = "/girls/{id}")
    public Girl getGirlById(@PathVariable Integer id){
        return girlRepository.findOne(id);
    }

    @PostMapping(value = "/girlAdd")
    public Result addOneGirl(@Valid Girl girl, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            //取第一个FieldError
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());
        girl.setMoney(girl.getMoney());
        return ResultUtil.success(girlRepository.save(girl));
    }

    @PutMapping(value = "/girlUpdate/{id}")
    public Girl updateOneGirl(@PathVariable Integer id,
                              @RequestParam Integer age,
                              @RequestParam String cupSize){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        return girlRepository.save(girl);
    }

    @DeleteMapping(value = "/girlDelete/{id}")
    public void deleteOneGirl(@PathVariable Integer id){
        girlRepository.delete(id);
    }

    @GetMapping(value = "/addTwoGirls")
    public String addTwoGirls(){
        girlService.insertTwo();
        return "insert succeed!";
    }
}
